package com.bocloud.cmp.service.config;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bocloud.cmp.dao.MessageDao;
import com.bocloud.cmp.entity.Message;
import com.bocloud.cmp.enums.MessageStatus;
import com.bocloud.cmp.interfaces.config.MessageService;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.Sign;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.MapTools;
import com.bocloud.coordinator.harmony.HarmonyLock;
import com.bocloud.coordinator.harmony.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service("messageService")
public class MessageServiceImpl implements MessageService {

	private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private LockFactory lockFactory;

	@Override
	public BsmResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple,
			Long userId) {
		GridBean gridBean = null;
		try {
			if (null == params) {
				params = Lists.newArrayList();
			}
			params.add(new Param(MapTools.simpleMap("ownerId", userId), Sign.EQ));
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("gmtCreate", Common.ONE);
			int total = this.messageDao.count(params);
			if (simple) {
				List<SimpleBean> beans = this.messageDao.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				List<Message> list = this.messageDao.list(page, rows, params, sorter);
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BsmResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Query message list error:", e);
			return new BsmResult(false, "查询失败");
		}
	}

	@Override
	public BsmResult create(Message message) {
		try {
			message.setStatus(MessageStatus.UNREAD.name());
			messageDao.save(message);
		} catch (Exception e) {
			logger.error("Create message error:", e);
			return new BsmResult(false, "添加失败");
		}
		return new BsmResult(true, message, "添加成功");
	}

	@Override
	public BsmResult remove(Long id, Long userId) {
		String path = Message.class.getSimpleName() + "_" + id;
		HarmonyLock lock = null;
		try {
			lock = lockFactory.getLock(path);
			if (!lock.acquire(path, 10, TimeUnit.SECONDS)) {
				logger.warn("Get harmonyLock time out!");
				return new BsmResult(false, "请求超时");
			}
			Message object = this.messageDao.query(id);
			if (null == object) {
				logger.warn("Message does not exist!");
				return new BsmResult(false, "数据不存在");
			}
			this.messageDao.remove(id, userId);
			return new BsmResult(true, "删除成功");
		} catch (Exception e) {
			logger.error("Remove message error:", e);
			return new BsmResult(false, "删除失败");
		} finally {
			if (null != lock) {
				lock.release();
			}
		}
	}

	@Override
	public BsmResult detail(Long id, Long userId) {
		try {
			Message message = this.messageDao.query(id);
			if (null == message) {
				return new BsmResult(false, "数据不存在");
			}
			if (message.getStatus().equals(MessageStatus.UNREAD.name())) {
				this.messageDao.updateStatus(id, MessageStatus.READ.name(), userId);
				message.setStatus(MessageStatus.READ.name());
			}
			return new BsmResult(true, message, "查询成功");
		} catch (Exception e) {
			logger.error("Get message error：", e);
			return new BsmResult(false, "查询失败");
		}
	}

}
